package org.geektimes.http.server.jdk.servlet;

import java.util.Collection;
import org.springframework.util.AntPathMatcher;

/**
 * Ant 语义匹配url.
 * <br> @author leo
 * <br> @date 2021/7/1
 * <br> @since 1.0.0
 */
public class AntUrlPatternsMatcher implements URLPatternsMatcher {

    /**
     * 匹配所有URL
     */
    private static final String MATCH_ALL = "/**";

    /**
     * 匹配所有
     */
    private static final String WILDCARD_MATCH_ALL = "**";

    private final AntPathMatcher antPathMatcher;

    public AntUrlPatternsMatcher(){
        this(true);
    }

    /**
     *
     * @param caseSensitive 是否忽略大小写.
     */
    public AntUrlPatternsMatcher(boolean caseSensitive) {
        antPathMatcher = new AntPathMatcher();
        antPathMatcher.setCaseSensitive(caseSensitive);
    }


    @Override
    public boolean matches(Collection<String> urlPatterns, String requestURI) {
        if (urlPatterns.contains(requestURI) || urlPatterns.contains(MATCH_ALL) || urlPatterns.contains(WILDCARD_MATCH_ALL)) {
            return true;
        }
       return urlPatterns.stream().anyMatch(pattern -> antPathMatcher.match(pattern,requestURI));
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE - 10;
    }
}
